import * as _ from 'lodash';
import koa from 'koa';
import fs from 'fs';

import env from '../../../env';

const getIndexHtml = function () {
  const INDEX_PATH = `${env.SERVER.STATIC_PATH}/index.html`;
  return fs.readFileSync(INDEX_PATH);
};

export default async function (ctx: koa.Context, next: koa.Next) {
  try {
    await next();
    const status = ctx.status || 404;
    if (status === 404) {
      ctx.throw(404);
    }
  } catch (err) {
    ctx.status = err.status || 500;
    if (ctx.status === 404) {
      ctx.status = 200;
      ctx.set('Content-Type', 'text/html');
      ctx.body = getIndexHtml();
    } else {
      throw err;
    }
  }
}
